package com.jz.netthings.core.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.jz.netthings.exception.AdscmSystemException;
import com.jz.netthings.support.SimpleCoreResponse;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author yyy
 * @ClassName AdscmCoreInterceptor
 * @Description TODO
 * @date 2018/8/6 14:54
 */
@Component
@Order(1000)
public class AdscmCoreInterceptor implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try{
            chain.doFilter(request,response);
        }catch (Exception e){
            HttpServletResponse resp = (HttpServletResponse)response;
            resp.setCharacterEncoding("UTF-8");
            resp.setHeader("Content-type", "text/html;charset=UTF-8");
            SimpleCoreResponse coreResponse = new SimpleCoreResponse("501", e.getMessage(), null);
            String json = JSONObject.toJSONString(coreResponse);
            resp.getWriter().print(json);
            resp.getWriter().flush();
//            resp.sendRedirect("/exception/response?eMsg="+ URLEncoder.encode(e.getMessage(),"UTF-8"));
        }
    }

    @Override
    public void destroy() {

    }
}
